<template>
  <el-drawer size="80%" :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="文件名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入文件名称" />
      </el-form-item>
      <el-form-item label="文件类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择文件类型" style="width: 100%">
          <el-option label="文件夹" value="folder" />
          <el-option label="文件" value="file" />
        </el-select>
      </el-form-item>
      <el-form-item label="文件路径" prop="path">
        <el-input v-model="formData.path" placeholder="请输入文件路径" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { FileApi, type FileVO } from '@/api/agent/manage/file'

defineOptions({ name: 'FileForm' })

const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formData = ref({
  id: undefined,
  name: undefined,
  type: 'file',
  path: undefined
})

const formRules = reactive({
  name: [{ required: true, message: '文件名称不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '文件类型不能为空', trigger: 'change' }],
  path: [{ required: true, message: '文件路径不能为空', trigger: 'blur' }]
})

const formRef = ref()

const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增文件' : '编辑文件'
  
  if (id) {
    formLoading.value = true
    try {
      formData.value = await FileApi.getFile(id)
    } finally {
      formLoading.value = false
    }
  } else {
    formData.value = {
      id: undefined,
      name: undefined,
      type: 'file',
      path: undefined
    }
  }
}

defineExpose({ open })

const emit = defineEmits(['success'])

const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  
  try {
    const data = formData.value as unknown as FileVO
    if (formData.value.id) {
      await FileApi.updateFile(data)
      message.success('更新成功')
    } else {
      await FileApi.createFile(data)
      message.success('创建成功')
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>